/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.DiskArray;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Storage;
import it.polimi.games.epkb.entityClasses.Component;
import java.util.ArrayList;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class DiskArrayJpaController implements Serializable {

    public DiskArrayJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public DiskArrayJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(DiskArray diskArray) throws IllegalOrphanException, PreexistingEntityException, Exception {
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = diskArray.getComponent();
        if (componentOrphanCheck != null) {
            DiskArray oldDiskArrayOfComponent = componentOrphanCheck.getDiskArray();
            if (oldDiskArrayOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type DiskArray whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Storage idStorage = diskArray.getIdStorage();
            if (idStorage != null) {
                idStorage = em.getReference(idStorage.getClass(), idStorage.getId());
                diskArray.setIdStorage(idStorage);
            }
            Component component = diskArray.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                diskArray.setComponent(component);
            }
            em.persist(diskArray);
            if (idStorage != null) {
                idStorage.getDiskArrayCollection().add(diskArray);
                idStorage = em.merge(idStorage);
            }
            if (component != null) {
                component.setDiskArray(diskArray);
                component = em.merge(component);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findDiskArray(diskArray.getId()) != null) {
                throw new PreexistingEntityException("DiskArray " + diskArray + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(DiskArray diskArray) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DiskArray persistentDiskArray = em.find(DiskArray.class, diskArray.getId());
            Storage idStorageOld = persistentDiskArray.getIdStorage();
            Storage idStorageNew = diskArray.getIdStorage();
            Component componentOld = persistentDiskArray.getComponent();
            Component componentNew = diskArray.getComponent();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                DiskArray oldDiskArrayOfComponent = componentNew.getDiskArray();
                if (oldDiskArrayOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type DiskArray whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idStorageNew != null) {
                idStorageNew = em.getReference(idStorageNew.getClass(), idStorageNew.getId());
                diskArray.setIdStorage(idStorageNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                diskArray.setComponent(componentNew);
            }
            diskArray = em.merge(diskArray);
            if (idStorageOld != null && !idStorageOld.equals(idStorageNew)) {
                idStorageOld.getDiskArrayCollection().remove(diskArray);
                idStorageOld = em.merge(idStorageOld);
            }
            if (idStorageNew != null && !idStorageNew.equals(idStorageOld)) {
                idStorageNew.getDiskArrayCollection().add(diskArray);
                idStorageNew = em.merge(idStorageNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setDiskArray(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setDiskArray(diskArray);
                componentNew = em.merge(componentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = diskArray.getId();
                if (findDiskArray(id) == null) {
                    throw new NonexistentEntityException("The diskArray with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DiskArray diskArray;
            try {
                diskArray = em.getReference(DiskArray.class, id);
                diskArray.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The diskArray with id " + id + " no longer exists.", enfe);
            }
            Storage idStorage = diskArray.getIdStorage();
            if (idStorage != null) {
                idStorage.getDiskArrayCollection().remove(diskArray);
                idStorage = em.merge(idStorage);
            }
            Component component = diskArray.getComponent();
            if (component != null) {
                component.setDiskArray(null);
                component = em.merge(component);
            }
            em.remove(diskArray);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<DiskArray> findDiskArrayEntities() {
        return findDiskArrayEntities(true, -1, -1);
    }

    public List<DiskArray> findDiskArrayEntities(int maxResults, int firstResult) {
        return findDiskArrayEntities(false, maxResults, firstResult);
    }

    private List<DiskArray> findDiskArrayEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(DiskArray.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public DiskArray findDiskArray(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(DiskArray.class, id);
        } finally {
            em.close();
        }
    }

    public int getDiskArrayCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<DiskArray> rt = cq.from(DiskArray.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
